import {
    CRC16,
    stringToAsciiBytes,
    MsgType,
    DeviceMessageSend,
    DeviceMessageReceive,
    CommonConfirmReplyMsgBody,
    RecipeSendMsgBody,
    RecipeStepInfo,
    RecipeStartCookingMsgBody,
    ElectronicScaleFoodPreparationMsgBody,
    FoodWeightInfo,
    RangeHoodFanControlMsgBody,
    SettingSeasoningRatioCalibrationMsgBody,
    SeasoningRatioCalibrationInfo,
    ManualAddSeasoningMsgBody,
    SeasoningAddInfo,
    SettingSeasoningBaseUnitMsgBody,
} from '@/utils/deviceProtocolUtil.js'

import {
    DeviceModel, 
    DeviceStatus,
    DeviceConnectStatus
} from '@/interface/device.js'

import { deviceProtocolListenerService } from './deviceProtocolListenerService'
import { DeviceProtocolBase } from './DeviceProtocolBase'
import { result } from 'lodash-es'

/**
 * 设备协议服务
 */
class DeviceProtocolService extends DeviceProtocolBase {
    constructor() {
        super()
    }

    /**
     * 初始化UDP、TCP网络服务
     */
    setupNetworkServer() {
        console.log("启动UDP Server");
        this.deviceDiscoverStore.startUdpServer()
        try {
            console.log("启动TCP Server");
            this.deviceProtocolStore.startTcpServer()
        } catch (error) {
            console.log("启动TCP出错: ", error);
        }
        console.log("注册事件监听器");
        deviceProtocolListenerService.registerDeviceMessageListener()

        // 刷新设备在线状态
        nextTick(_ => {
            this.deviceStore = useOutsideDeviceStore()
            this.refreshDeviceOnlineStatus()
        })
    }
    /**
     * 停止网络服务
     */
    destroyNetworkServer() {
        console.log("停止UDP Server");
        this.deviceDiscoverStore.stopUdpServer()
        console.log("停止TCP Server");
        this.deviceProtocolStore.stopTcpServer()
        console.log("注销事件监听器");
        deviceProtocolListenerService.unregisterdeviceMessageListener()
    }
    
    /**
     * 网络服务监控程序
     * 监测TCP、UDP服务程序，如果挂掉就自动重启
     */
    networkServerWatcher() {
        const intervalId = setInterval(() => {
          // 每10s检测一次
          try {
            if (!this.deviceDiscoverStore.isUdpAlive()) {
                console.log("UDP协议服务异常");
                // 重启UDP服务
                console.log("停止UDP Server");
                this.deviceDiscoverStore.stopUdpServer()
                console.log("重新启动UDP Server");
                this.deviceDiscoverStore.startUdpServer()
            } else {
                // console.log("UDP协议服务正常");
            }
          } catch (error) {
            console.log("重启UDP出错: ", error);
          }
          
          try {
              this.deviceProtocolStore.isTcpAlive()
              .then(result => {
                  if (!result) {
                      console.log("TCP协议服务异常");
                      // 重启TCP服务
                      console.log("停止TCP Server");
                      this.deviceProtocolStore.stopTcpServer()
                      console.log("启动TCP Server");
                      this.deviceProtocolStore.startTcpServer()
                  } else {
                    // console.log("TCP协议服务正常");
                }
              })
          } catch (error) {
            console.log("重启TCP出错: ", error);
          }
        }, 10000);
    }
    
    /**
     * 刷新设备在线状态
     * 如果APP被手动kill掉，APP保存的设备在线状态可能是不对的
     */
    refreshDeviceOnlineStatus() {
        const { bindDeviceList } = storeToRefs(this.deviceStore)
        const deviceSessionList = this.deviceProtocolStore.getDeviceSessionList()
        // console.log("绑定的设备列表：", bindDeviceList.value)
        // console.log("设备会话列表：", deviceSessionList)

        if (deviceSessionList) {
            bindDeviceList.value.forEach(device => {
                const deviceSessionObj = deviceSessionList.find(
                  item => item.sn === device.sn
                )
                if (deviceSessionObj) {
                    // 设备会话存在
                    device.onlineStatus = DeviceConnectStatus.Online
                } else {
                    // 设备会话不存在，离线
                    device.onlineStatus = DeviceConnectStatus.Offline
                }
            })
        } else {
            bindDeviceList.value.forEach.forEach(device => {
                device.onlineStatus = DeviceConnectStatus.Offline
            })
        }
    }
}

export const deviceProtocolService = new DeviceProtocolService()